import React, { useEffect, forwardRef, useImperativeHandle } from 'react';
import { Spin, Row, Col, Space, Select } from 'antd';
import { features, useTablePipeline } from 'ali-react-table';
import 'echarts-gl';

import { useTRState } from '#/utils/trHooks.jsx';
import { TjChart, TjTable } from '@/pages/ETrade/components';
// TjSegmented
import { export_json_to_excel } from '@/utils/fileExport.js';
import { ChartTitle } from '../components';
import FullModel from '../components/FullModel';
import { DATA_MAP, getTableColumns, fmtData, typeOptions, getConnectingLineData } from './helper';
import { getRunDataList, getSpotPrice } from '../services';
import styles from './index.less';
import { useThemeChange } from '@/hooks';

// 山东
export default forwardRef(({ formValue, stations, marketName }, ref) => {
  const _charts = [
    'spotPrice',
    'biddingSpaceCorrelationMap',
    // 'provinceLoadLink',
    // 'newEnergy',
    // 'provinceLoadLinkNewEnergy',
    // 'provinceLoadNewEnergy',
    // 'baseDecompositionProportion',
    // 'provinceLoad',
    // 'link',
    // 'setTheStandby',
    'backupInformation',
    'provincialLoad',
    'newEnergy',
    'connectingLine',
  ];
  const _table = [
    'spotPrice',
    // 'provinceLoadLinkNewEnergy',
    // 'provinceLoadLink',
    // 'provinceLoadNewEnergy',
    'provincialLoad',
    'connectingLine',
    'newEnergy',
    // 'baseDecompositionProportion',
    'backupInformation',
  ];
  const [state, setState] = useTRState({
    loading: true,
    loadingSpot: true,
    loadingRunData: true,
    // 场站
    stationName: stations?.[0]?.label || '',
    // form
    stationId: stations?.[0]?.value || null,
    // isRevised: 1, // 修正前(0)/后(1)
    // result
    dataMap: {}, // 原始数据(未处理)
    tableColumns: [], // 表头
    tableData: [], // 表数据
    charts: {}, // 图配置 charts[key] 与 _charts[key] 对应
    datetimes: [], // 时间刻度
    connectingLineType: 'total',
    newEnergyType: 'total',
  });
  const { theme } = useThemeChange();

  useImperativeHandle(ref, () => ({
    onFetch,
    onExport,
  }));

  useEffect(() => {
    // 表头、时间刻度：依赖时间范围、点位类型
    const tableColumns = getTableColumns(formValue);
    const datetimes = tableColumns.slice(1).map((x) => x.name);
    setState({
      datetimes,
      tableColumns,
    });
  }, [formValue.startDate, formValue.endDate, formValue.type]);

  useEffect(() => {
    // 数据全部获取后处理
    if (state.loadingSpot) return;
    if (Object.keys(state.dataMap).length < _charts.length) return;
    setTimeout(() => {
      const { charts, tableData } = fmtData({
        dataMap: state.dataMap,
        datetimes: state.datetimes,
        // isRevised: state.isRevised,
        stationName: state.stationName,
        chartKeys: _charts,
        tableKeys: _table,
      });
      setState({
        charts,
        tableData,
      });
    }, 1);
  }, [JSON.stringify(state.dataMap), state.loadingSpot, theme]);
  // state.isRevised

  /** 数据处理 */
  async function onFetch() {
    setState({ loading: true });
    await Promise.all([onFetchData(), onFetchSpot()]);
    setState({ loading: false });
  }
  function onExport() {
    if (state.loading || state.loadingSpot) return;
    // 导出
    let exportData = [];
    state.tableData.map(({ groupTitle, children }) => {
      exportData.push([groupTitle]);
      exportData = exportData.concat(
        children.map((c) => state.tableColumns.map(({ code }) => c[code])),
      );
    });
    const params = {
      header: state.tableColumns.map((c) => c.name),
      data: exportData,
      filename: `运行数据披露-${marketName}`,
    };
    export_json_to_excel(params);
  }

  async function onFetchSpot() {
    // 现货价格、竞价空间
    setState({ loadingSpot: true });
    const { stationId } = state;
    const res = await getSpotPrice({ ...formValue, stationId });
    state.dataMap = {
      ...state.dataMap,
      ...(res?.runDataPointBodyMap || {}),
      biddingSpaceCorrelationMap: res?.biddingSpaceCorrelationMap || {},
    };
    setState({
      dataMap: state.dataMap,
      loadingSpot: false,
    });
    return Promise.resolve();
  }

  async function onFetchData() {
    // 其他数据
    setState({ loadingRunData: true });
    const { connectingLineType, newEnergyType } = state;
    let {
      provincialLoad = [],
      connectingLine = [],
      backupInformation = [],
      newEnergy = [],
    } = await getRunDataList({
      ...formValue,
      connectingLineType,
      newEnergyType,
    });
    // if (connectingLineType === 'branch') {
    //   connectingLine = getConnectingLineData(connectingLine);
    // }
    state.dataMap = {
      ...state.dataMap,
      provincialLoad,
      connectingLine,
      backupInformation,
      newEnergy,
    };
    setState({
      dataMap: state.dataMap,
      loadingRunData: false,
    });
    return Promise.resolve();
  }

  /** 方法 */
  const onChangeStation = (v, opt) => {
    // 场站切换
    state.stationId = v;
    state.stationName = opt.label;
    setState({
      stationId: state.stationId,
      stationName: state.stationName,
    });
    onFetchSpot();
  };

  const onChangeType = (v, opt, key) => {
    // 总分切换
    state[key] = v;
    setState({
      [key]: v,
    });
    onFetchData();
  };

  // const onChangeRevised = (isRevised) => {
  //   state.isRevised = isRevised;
  //   setState({ isRevised });
  // };

  /** render */
  const pipeline = useTablePipeline()
    .input({
      columns: state.tableColumns,
      dataSource: state.tableData,
    })
    .primaryKey('id')
    .use(features.rowGrouping({ defaultOpenAll: true }))
    .appendRowPropsGetter((record) => {
      const color = !!record.groupTitle ? '#2D3133' : '#222629';
      return {
        style: { '--bgcolor': color, '--hover-bgcolor': color },
      };
    });

  // 所有图
  const _renderCharts = () =>
    _charts.map((key) => {
      const { group, ...titleProps } = DATA_MAP[key] || {};
      const runDataKeys = ['connectingLine', 'newEnergy']; //总-分
      const soptKeys = ['spotPrice', 'biddingSpaceCorrelationMap'];
      const bigger = ['connectingLine', 'newEnergy', 'provincialLoad']; //放大两列齐高
      const selfSoptsLoading = soptKeys.includes(key);
      const selfRunDataLoading = runDataKeys.includes(key);
      let height = 200;
      if (bigger.includes(key)) {
        height = 288;
      }
      if (selfRunDataLoading) {
        //新能源
        //联络线
        titleProps.right = (
          <Space size={16}>
            <Select
              style={{ width: 200 }}
              value={state[`${key}Type`]}
              options={typeOptions[key]}
              optionFilterProp="label"
              showSearch
              showArrow
              onChange={(...e) => {
                onChangeType(...e, `${key}Type`);
              }}
              getPopupContainer={(e) => e.parentNode}
            />
          </Space>
        );
      }
      if (key === 'spotPrice') {
        // 现货价格
        titleProps.right = (
          <Space size={16}>
            <Select
              style={{ width: 200 }}
              value={state.stationId}
              options={stations}
              optionFilterProp="label"
              showSearch
              showArrow
              onChange={onChangeStation}
              getPopupContainer={(e) => e.parentNode}
            />
            {/* <TjSegmented
              value={state.isRevised}
              options={[
                { label: '修正前', value: 0 },
                { label: '修正后', value: 1 },
              ]}
              onChange={onChangeRevised}
            /> */}
          </Space>
        );
      }
      if (key === 'biddingSpaceCorrelationMap') {
        // 现货价格&竞价空间相关性
        titleProps.right = (
          <div className={styles.right_box}>
            <FullModel>
              <div className={styles.col} key={key}>
                <Spin spinning={selfSoptsLoading && !state.loading && state.loadingSpot}>
                  <div>
                    <ChartTitle {...titleProps} />
                    <TjChart
                      style={{ height: 'calc(100vh - 88px)' }}
                      option={state.charts?.[key] || null}
                      group={group}
                    />
                  </div>
                </Spin>
              </div>
            </FullModel>
            <div style={{ color: '#7A7D7F' }}>{state.stationName}</div>
          </div>
        );
        height = 464;
      }

      return (
        <div className={styles.col} key={key}>
          <Spin
            spinning={
              !state.loading &&
              (selfSoptsLoading & state.loadingSpot || (selfRunDataLoading && state.loadingRunData))
            }
          >
            <div>
              <ChartTitle {...titleProps} />
              <TjChart style={{ height }} option={state.charts?.[key] || null} group={group} />
            </div>
          </Spin>
        </div>
      );
    });

  return (
    <div>
      <Spin spinning={state.loading}>
        <div className={styles.rows}>{_renderCharts()}</div>
        <div>
          <TjTable
            isLoading={!state.loading && state.loadingSpot}
            useVirtual="auto"
            defaultColumnWidth={90}
            {...pipeline.getProps()}
          />
          <div style={{ height: 24 }} />
        </div>
      </Spin>
    </div>
  );
});
